<template>
  <div class="article-search-container">
    <div class="search-header">
      <h1 class="search-title">搜索结果: "{{ keyword }}"</h1>
    </div>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    
    <div v-else-if="articles.length === 0" class="empty-state">
      <div class="empty-icon">
        <t-icon name="search" size="large" />
      </div>
      <h3>没有找到相关文章</h3>
      <p>尝试使用其他关键词搜索</p>
      <el-button type="primary" round @click="$router.push('/home')">返回首页</el-button>
    </div>
    
    <div v-else class="article-list">
      <div v-for="article in articles" :key="article.id" class="article-card">
        <div class="article-header">
          <div class="user-info" v-if="userMap[article.userId]">
            <img 
              :src="userMap[article.userId].profilePicture || defaultAvatar" 
              :alt="userMap[article.userId].username" 
              class="user-avatar"
            >
            <div class="user-details">
              <span class="username">{{ userMap[article.userId].username }}</span>
              <span class="publish-time">{{ formatDate(article.createdAt) }}</span>
            </div>
          </div>
        </div>
        
        <div class="article-content" @click="navigateToArticle(article.id)">
          <h2 class="article-title">{{ article.title }}</h2>
          <p class="article-description">{{ article.description }}</p>
        </div>
        
        <div class="article-footer">
          <div class="article-stats">
            <div class="stat-item">
              <t-icon name="thumb-up" />
              <span>{{ article.likeCount || 0 }}</span>
            </div>
            <div class="stat-item">
              <t-icon name="star" />
              <span>{{ article.favoriteCount || 0 }}</span>
            </div>
            <div class="stat-item">
              <t-icon name="message" />
              <span>{{ article.commentCount || 0 }}</span>
            </div>
          </div>
          <div class="read-more">
            <span>阅读全文</span>
            <t-icon name="arrow-right" />
          </div>
        </div>
      </div>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getPublishedArticlesByKeyWordOrderByDESC } from '@/api/articleApi';
import { findUserById } from '@/api/userApi';
import { ElMessage } from 'element-plus';
import defaultAvatar from '@/imgs/avatar.png';

const route = useRoute();
const router = useRouter();

const articles = ref([]);
const userMap = ref({});
const loading = ref(true);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

const keyword = computed(() => route.params.keyword);

const fetchArticles = async () => {
  loading.value = true;
  try {
    const response = await getPublishedArticlesByKeyWordOrderByDESC(
      keyword.value,
      currentPage.value,
      pageSize.value
    );
    
    articles.value = response.data || [];
    total.value = articles.value.length || 0;
    
    // Fetch user info for each article
    await Promise.all(
      articles.value.map(async (article) => {
        if (!userMap.value[article.userId]) {
          try {
            const userResponse = await findUserById(article.userId);
            userMap.value[article.userId] = userResponse.data;
          } catch (error) {
            console.error(`Failed to fetch user info for ID ${article.userId}:`, error);
          }
        }
      })
    );
  } catch (error) {
    console.error('Failed to fetch articles:', error);
    ElMessage.error('获取文章列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

const formatDate = (dateString) => {
  if (!dateString) return '';
  
  const date = new Date(dateString);
  const now = new Date();
  const diffMs = now - date;
  const diffMins = Math.floor(diffMs / (1000 * 60));
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
  
  if (diffMins < 60) {
    return `${diffMins} 分钟前`;
  } else if (diffHours < 24) {
    return `${diffHours} 小时前`;
  } else if (diffDays < 30) {
    return `${diffDays} 天前`;
  } else {
    return date.toLocaleDateString('zh-CN', { 
      year: 'numeric', 
      month: 'long', 
      day: 'numeric' 
    });
  }
};

const navigateToArticle = (id) => {
  router.push(`/home/article/${id}`);
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchArticles();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchArticles();
};

watch(() => route.params.keyword, () => {
  currentPage.value = 1;
  fetchArticles();
});

onMounted(() => {
  fetchArticles();
});
</script>

<style scoped>
.article-search-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
  min-height: 100vh;
}

.search-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid #eaeaea;
}

.search-title {
  font-size: 24px;
  color: #333;
  font-weight: 600;
  margin: 0;
  position: relative;
  display: inline-block;
}

.search-title::after {
  content: '';
  position: absolute;
  bottom: -16px;
  left: 0;
  width: 60px;
  height: 3px;
  background: linear-gradient(90deg, #409EFF, #a0cfff);
  border-radius: 3px;
}

.loading-container {
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 0;
  color: #909399;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.empty-icon {
  background: #f0f5ff;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16px;
  color: #409EFF;
}

.empty-state h3 {
  margin: 16px 0 8px;
  font-size: 20px;
  color: #333;
}

.empty-state p {
  margin-bottom: 24px;
  font-size: 16px;
}

.article-list {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.article-card {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  border: 1px solid #eaeaea;
}

.article-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.12);
}

.article-header {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fafafa;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 12px;
  border: 2px solid white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.user-details {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: 600;
  font-size: 15px;
  color: #333;
}

.publish-time {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

.article-content {
  padding: 24px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.article-content:hover {
  background-color: #f9f9f9;
}

.article-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 16px;
  line-height: 1.4;
}

.article-description {
  font-size: 15px;
  color: #606266;
  line-height: 1.6;
  margin: 0;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.article-footer {
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fafafa;
}

.article-stats {
  display: flex;
  gap: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #606266;
  font-size: 14px;
  transition: color 0.2s;
}

.stat-item:hover {
  color: #409EFF;
}

.read-more {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #409EFF;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: transform 0.2s;
}

.read-more:hover {
  transform: translateX(3px);
}

.pagination-container {
  margin-top: 40px;
  display: flex;
  justify-content: center;
  background: white;
  padding: 16px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}
</style>
